package com.quanliang.org.crawlerquanliang.utils;

import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;

import java.io.FileInputStream;
import java.io.InputStream;


/**
 * excel工具类
 *
 * @author FYM
 * @data 2022/8/26 14:55
 */
public class ExcelUtil {
    /**
     * 初始化HSSFWorkbook
     */
    public static HSSFWorkbook initHSSFWorkbook(String sheetName, String[] title) {
        HSSFWorkbook hwb = new HSSFWorkbook();
        //创建sheet
        HSSFSheet sheet = hwb.createSheet(sheetName);
        //第一行
        HSSFRow row = sheet.createRow(0);
        //创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = hwb.createCellStyle();
        //声明列对象
        HSSFCell cell = null;
        //创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        return hwb;
    }

    
    /**
     * 将图片插入excel中
     */
    @SneakyThrows()
    public static void insertImg(HSSFWorkbook wb, HSSFSheet sheet, HSSFRow row, String imgLocal, int rowNum) {
        //row.createCell(4).setCellValue(imgLocal);
        InputStream is = new FileInputStream(imgLocal);
        byte[] bytes = IOUtils.toByteArray(is);
        int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
        CreationHelper helper = wb.getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();
        Drawing drawing = sheet.createDrawingPatriarch();

        anchor.setCol1(4); // param1是列号
        anchor.setRow1(rowNum); // param2是行号

        // 插入图片
        Picture pict = drawing.createPicture(anchor, pictureIdx);

        // 调整图片占单元格百分比的大小，1.0就是100%
        pict.resize(1.0);
    }


}
